package com.nitty.cash.loop.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import com.nitty.cash.loop.R
import com.nitty.cash.loop.base.app.NittyStackManager
import com.nitty.cash.loop.common.CommonActivity
import com.nitty.cash.loop.configs.NittyConfigs
import com.nitty.cash.loop.databinding.UiLoginBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.ui.presenter.LoginPresenter
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * Nitty
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class LoginAct: CommonActivity(), IViewContract.ILoginView {
    lateinit var binding: UiLoginBinding
    private var presenter: LoginPresenter? = null

    override fun getNittyRootView(): View {
        binding = UiLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initNittyView() {
        NittyTitleBarUtil.setStatusBarLightMode(this, false)
        setNittyTitleBarVisibility(View.GONE)
        setNittyRootBackgroundLableRes(R.mipmap.nitty_withdraw_titlebar_bg)
        setNittyRootParentBackgroundColors(Color.parseColor("#ffffd451"), Color.parseColor("#ffffac17"))
        //关闭所有页面
        NittyStackManager.finishAllActivity(LoginAct::class.java)
        checkLoginBtnState()
    }

    override fun initNittyListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Login Page")
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_CUSTOMER,"Login Page")
        }

        binding.editMobile.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {
                }
                else -> {
                    addEventPointRequestAction(NittyEventPointType.FORM.NITTY_FORM_LOGIN_MOBILE, getUserLoginMobile())
                }
            }
        }
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.loginPPCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOGIN_PRIVACY_AGREE)
                }
                false -> {
                    addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener {
            addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_LOGIN_NEXT,getUserLoginMobile())
            onHideSoftInput(binding.editMobile)
            presenter?.requestUserLoginAction()
        }

        //隐私协议
        binding.textLoginPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.privacy_policy_title)
            val linkUrl = NittyConfigs.NITTY_PRIVACY_POLICY_LINK
            WebAct.start(this,showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun loadNittyData() {
        if (presenter == null){
            presenter = LoginPresenter(this)
        }
        binding.textLoginZoneCode.text = "+${NittySharedHelper.getNittySharedString(NittySharedKey.NITTY_TIMEZONE_CODE)}"

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.privacy_policy_title))
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFD5118")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textLoginPrivacyPolicy.text = spString

        //等待时间
        binding.textLoginUpTime.text = String.format(getString(R.string.login_up_time),NittyConfigsHelper.getNittyLoginUpTime())
        //默认额度
        binding.textLoginDefaultAmount.text = NittyConfigsHelper.getNittyDefaultAmount()
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        binding.loginErrorLayout.visibility = View.INVISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFFFFFF"))
            .setStrokeColor(Color.parseColor("#FFFFFFFF"))
            .setShadowColor(Color.parseColor("#404A250C"))
            .setShadowSize(resources.getDimension(com.lib.common.R.dimen.dp_10).toInt())
            .intoBackground()
        binding.editMobile.setTextColor(Color.parseColor("#FF000000"))
        if (binding.loginPPCheckBox.isChecked && getUserLoginMobile().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    override fun getUserLoginMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    override fun showUserLoginFailure(data: JSONObject) {
        binding.loginErrorLayout.visibility = View.VISIBLE
        binding.loginMobileLayout.shapeDrawableBuilder
            .setSolidColor(Color.parseColor("#FFFFF7F7"))
            .setStrokeColor(Color.parseColor("#FFFD5118"))
            .setShadowColor(Color.parseColor("#404A250C"))
            .setShadowSize(resources.getDimension(com.lib.common.R.dimen.dp_10).toInt())
            .intoBackground()
        binding.editMobile.setTextColor(Color.parseColor("#FFFF4343"))
    }

    override fun showUserLoginMainPage() {
        onIntent(NittyTabAct::class.java)
        finish()
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(NittyEventPointType.PAGE.NITTY_PAGE_LOGIN_END)
    }
}